package com.atguigu.crowd.service.impl;

import com.atguigu.crowd.constant.CrowdContant;
import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.entity.AdminExample;
import com.atguigu.crowd.entity.AdminExample.Criteria;
import com.atguigu.crowd.exception.LoginAcctAlreadyInUserException;
import com.atguigu.crowd.exception.LoginFailedException;
import com.atguigu.crowd.mapper.AdminMapper;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.util.CrowdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private PasswordEncoder   passwordEncoder;

    public void saveAdmin(Admin admin) {
        String userPswd = admin.getUserPswd();

        String encode = passwordEncoder.encode(userPswd);
        admin.setUserPswd(encode);
        adminMapper.insert(admin);

    }

    public List<Admin> getAll() {
        return adminMapper.selectByExample(null);
    }


    public Admin getAdminByloginAcct(String loginAcct,String userPswd) {
        //创建AdminExample对象
        AdminExample adminExample = new AdminExample();

        //创建Criteria对象
        Criteria criteria = adminExample.createCriteria();
        //拼接查询条件
        criteria.andLoginAcctEqualTo(loginAcct);

        List<Admin> list = adminMapper.selectByExample(adminExample);


        if (list==null || list.size()==0){
            throw new LoginFailedException(CrowdContant.MESSAGE_LOGIN_FAILED);
        }

        if (list.size()>1){
            throw new RuntimeException(CrowdContant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }


        Admin admin = list.get(0);
        //如果为空判断
        if (admin==null) {

            throw new LoginFailedException(CrowdContant.MESSAGE_LOGIN_FAILED);
        }

        String userPswdDB= admin.getUserPswd();

        //进行密码加密
        String rePswd = CrowdUtil.MD5(userPswd);

        //密码一致性判断
        if (!Objects.equals(userPswdDB,rePswd)){

            //密码不一致
            throw new LoginFailedException(CrowdContant.MESSAGE_LOGIN_FAILED);
        }

        return admin;
    }

    @Override
    public Admin getAdminByloginAcct(String loginAcct) {
        AdminExample example = new AdminExample();

        Criteria criteria = example.createCriteria();

        criteria.andLoginAcctEqualTo(loginAcct);
        List<Admin> admins = adminMapper.selectByExample(example);

        Admin admin = admins.get(0);
        return admin;
    }

    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {

        //PageHelper调方法开启分页功能
        PageHelper.startPage(pageNum,pageSize);

        //执行查询
        List<Admin> list = adminMapper.selectByKeyWord(keyword);


        System.out.println(list);

        return new PageInfo<>(list);
    }

    @Override
    public void remove(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public void add(Admin admin) {
        //密码加密
        String userPswd=admin.getUserPswd();
        userPswd=passwordEncoder.encode(userPswd);
        admin.setUserPswd(userPswd);

        //生成创建时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = dateFormat.format(date);
        admin.setCreateTime(createTime);
        // 执行保存，如果账户被占用会抛出异常
        try { adminMapper.insert(admin);
        }
        catch (Exception e) {
            e.printStackTrace();
            // 检测当前捕获的异常对象，如果是 DuplicateKeyException 类型说明是账号重复导 致的
             if(e instanceof DuplicateKeyException) {
                 // 抛出自定义的 LoginAcctAlreadyInUseException 异常
                  throw new LoginAcctAlreadyInUserException(CrowdContant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE); }
        }
    }

    @Override
    public void update(Admin admin) {

        adminMapper.updateByPrimaryKeySelective(admin);

    }

    @Override
    public void saveAdminRoleRelationship(Integer adminId, List<Integer> roleIdList) {

        //根据adminid删除旧的关联数据
        adminMapper.deleteOldRelationship(adminId);

        //根据adminId和roleIdList保存新的关联关系
        if (roleIdList!=null&& roleIdList.size()>0){

            adminMapper.insertNewRelationship(adminId,roleIdList);

        }
    }

    @Override
    public Admin getAdminById(Integer adminId) {

        Admin admin = adminMapper.selectByPrimaryKey(adminId);

        return admin;
    }
}
